package com.zcw.rabbitmq.util;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class RabbitConnectionUtil {

    // rabbit ip
    private static final String HOST = "47.109.83.49";
    // Rabbit 端口
    private static final int PROT = 15672;
   // 登录用户名
    private static final String USER_NAME = "zcw";
    // 登录密码
    private static final String PASSWORD = "zcw";

    private static String EXCANGE_NAME = "queueOne";
    private static String QUEUE_NAME = "queueOne";

    public static String MEBER_QUEUE_NAME1 = "member_queue_1";

    public static String MEBER_QUEUE_NAME2 = "member_queue_2";


    private static Connection connection = null;



    public static final String getExchangeName(){
        return EXCANGE_NAME;
    }

    public static final String getQueueName(){
        return QUEUE_NAME;
    }

    /**
     * 创建RabbitMQ的连接并生成信道
     * @return
     */
    public static Channel getRabbitConnection(){
        try {
            ConnectionFactory connectionFactory = new ConnectionFactory();
            connectionFactory.setHost(HOST);
//        connectionFactory.setPort(PROT);
            connectionFactory.setUsername(USER_NAME);
            connectionFactory.setPassword(PASSWORD);
            Connection connection = connectionFactory.newConnection();
            return connection.createChannel();
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        } catch (TimeoutException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取单例的RabbitMQ连接，避免多次new占用资源
     * @return
     */
    public static Connection getSingleRabbitConnection(){
        try {
            ConnectionFactory connectionFactory = new ConnectionFactory();
            connectionFactory.setHost(HOST);
            connectionFactory.setUsername(USER_NAME);
            connectionFactory.setPassword(PASSWORD);
            if (connection ==null) connection = connectionFactory.newConnection();

            return connection;
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        } catch (TimeoutException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    public static void closeRabbitConnection(){
        Connection connection = getSingleRabbitConnection();
        if (connection != null) {
            try {
                connection.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            } finally {
                /*try {
                    connection.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }*/
            }
        }
    }

}
